package com.zhou.mymvpdemo.Utils;

import android.support.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/2.
 */


    /**
     * Created by yaoluhao on 31/07/2017.
     */

    public class CheckUtils {
        public static void checkNotNulls(Object... reference) {
            List<Integer> nullObject = null;
            for (int i = 1; i < reference.length; i++) {
                if (reference[i] == null) {
                    if (nullObject == null) {
                        nullObject = new ArrayList<>();
                    }
                    nullObject.add(i);
                }
            }
            if (nullObject != null){
                throw new NullPointerException("The indexs of null point are: "+nullObject.toString());
            }
        }

        public static <T> T checkNotNull(T reference) {
            if (reference == null) {
                throw new NullPointerException();
            } else {
                return reference;
            }
        }

        public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
            if (reference == null) {
                throw new NullPointerException(String.valueOf(errorMessage));
            } else {
                return reference;
            }
        }

        public static <T> T checkNotNull(T reference, @Nullable String errorMessageTemplate,
                                         @Nullable Object... errorMessageArgs) {
            if (reference == null) {
                throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs));
            } else {
                return reference;
            }
        }

        private static String format(String template, @Nullable Object... args) {
            if (args == null) {
                args = new Object[0];
            }
            template = String.valueOf(template);
            StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
            int templateStart = 0;

            int i;
            int placeholderStart;
            for (i = 0; i < args.length; templateStart = placeholderStart + 2) {
                placeholderStart = template.indexOf("%s", templateStart);
                if (placeholderStart == -1) {
                    break;
                }

                builder.append(template.substring(templateStart, placeholderStart));
                builder.append(args[i++]);
            }

            builder.append(template.substring(templateStart));
            if (i < args.length) {
                builder.append(" [");
                builder.append(args[i++]);

                while (i < args.length) {
                    builder.append(", ");
                    builder.append(args[i++]);
                }

                builder.append(']');
            }

            return builder.toString();
        }
    }


